package com.zhuhjay.common.base.util;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 校验工具类
 *
 * @author ZhuHJay
 * @date 2023/7/11 12:07
 */
public class ValidateUtils {

    /**
     * 校验对象
     *
     * @param t   校验对象
     * @param <T> 校验对象类型
     * @return 错误信息列表
     */
    public static <T> List<String> valid(T t) {
        Validator validatorFactory = Validation.buildDefaultValidatorFactory().getValidator();
        Set<ConstraintViolation<T>> errors = validatorFactory.validate(t);
        return errors.stream().map(ConstraintViolation::getMessage).collect(Collectors.toList());
    }

}
